//
//  OAuthViewController.swift
//  JKWeiBo
//
//  Created by 王冲 on 2017/6/25.
//  Copyright © 2017年 希爱欧科技有限公司. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {

    let appKey = "2202957917"
    let appSecret = "f482e170b0d6eae93b4abdfff285a9c8"
    let redirect_uri = "http://www.jianshu.com/u/8fed18ed70c9"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.red
        
        view.addSubview(webView)
        
        navigationItem.title = "安其拉之路";
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", style: UIBarButtonItemStyle.plain, target: self, action: #selector(OAuthViewController.click))

        // 1.获取未授权的RequestToken  要求 SSL 1.2版本
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(url: url! as URL)
        webView.loadRequest(request as URLRequest)
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        
        super.viewDidDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    
    private lazy var webView: UIWebView = {
    
        let webview = UIWebView(frame: CGRect(x: 0, y: 0, width: JKscreenW, height: JKscreenH))
        webview.delegate = self
        return webview
    
        }()
    
    func click(){
        
        dismiss(animated: true, completion: nil)
        
    }
}

extension OAuthViewController: UIWebViewDelegate{

    // 返回 true正常加载  false不加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
    
        /*
         加载授权界面
         https://api.weibo.com/oauth2/authorize?client_id=2202957917&redirect_uri=http://www.jianshu.com/u/8fed18ed70c9
        
         跳转到授权界面 
         https://api.weibo.com/oauth2/authorize
        
         授权成功
         http://www.jianshu.com/u/8fed18ed70c9?code=ed9df4b69d51158ad03d15a72ea8fa65
        
         取消授权
         http://www.jianshu.com/u/8fed18ed70c9?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        */
        
        print(request.url!.absoluteString)
        
        // 1.如果不是授权回调页,就继续加载
        if !request.url!.absoluteString.hasPrefix(redirect_uri) {
            
            // 继续加载
            return true
        }
        
        // 2.判断是否授权成功
        let codeStr = "code="
        if request.url!.query!.hasPrefix(codeStr) {
            
            // 授权成功 获取授权成功的RequestToken值
            print("授权成功")
            // 1.去除已经授权成功的RequestToken
            let code = request.url!.query?.substring(from: codeStr.endIndex)
            print(code!)
            // 2.利用已经授权的RequestToken来换取AccessToken
            loadAccessToken(code: code!);
            
        }else{
        
            // 取消授权
            print("取消授权")
            dismiss(animated: true, completion: nil)
        }
        
        return false
    
    }

    /*
     * 换取AccessToken
     * :param: code 已经授权的 RequestToken
     */
    private func loadAccessToken(code: String){
    
       // 1.定义路径
        let path = "oauth2/access_token"
       // 2.封装参数
        let params = ["client_id":appKey,"client_secret":appSecret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
    
        SVProgressHUD.show(withStatus: "正在加载")
        // 3.发送post请求
        NetworkTools.shareNetworkTools().post(path, parameters: params, progress: nil, success: { (
            _, JSON) in
            
            SVProgressHUD.dismiss()
            
            
            /** 验证 expires_in 不是字符串 */
            /*
            do{
            
              let data = try JSONSerialization.data(withJSONObject: JSON!, options: JSONSerialization.WritingOptions.prettyPrinted)
            
              let str =  NSString(data:data ,encoding: String.Encoding.utf8.rawValue)
                
                print(str!)
                
            }catch
            {
            
            
            }
            */
            
            /*
             *  结论:
                    同一个用户对同一个应用多次授权多次AccessToken是一样的，每个AccessToken都是有过期时间的:
                    1.如果自己对自己的应用授权，有效时间是5年差1天
                      2.如果其他人对你的应用进行授权，有效时间是3天
             */
            
            print(JSON!)
            
            // 1.字典转模型
            /*
             plist  : 特点是只能存储系统自带的数据类型,将对象转化为json之后写入文件中 -> 在公司中已经开始使用
             偏好设置 : 本质plist
             归档    : 可以存储自定义的对象
             数据库  : 用于存储大数据,特点是效率高
             */
            let account = UserAccount(dict: JSON! as! [String : AnyObject])
            print("数组打印出来的值\(account)")
            
            // 2.获取授权后的用户信息
            account.loadUserInfo(finished: { (account,error) in
                
                if account != nil{
                    
                    account?.saveAccount()
                    // 授权界面消失
                    self.click()
                    // 授权成功也保存了数据，接着就跳转到主控制器
                     NotificationCenter.default.post(name: NSNotification.Name(rawValue: switchRootViewController), object: false)
                    print(account!)
                    
                }else{
                    
                   SVProgressHUD.show(withStatus: "网络不给力...")
                }
               
            })
            
            // 3.在UserAccount里面进行用户归档模型
            
        }) { (_, error) in
           

            SVProgressHUD.show(withStatus: "网络不给力...")
            
        }
        
        
        print(path)
    }
    
    // MARK: 提示用户正在加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show(withStatus: "正在加载")
    
    }
    
    // MARK: 提示用户加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }

}



